package com.lsmw.msm.service.controller;

import com.lsmw.commonutils.R;
import com.lsmw.commonutils.RandomUtil;
import com.lsmw.msm.service.MsmService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

/*
 *ClassName:MsmController
 *UserName:二号男嘉宾
 *CreateTime:2020/12/23 19:20
 */
@RestController
@RequestMapping("/msm")
public class MsmController {

    private RedisTemplate<String, String> redisTemplate;

    private MsmService msmService;

    @Autowired
    public MsmController(RedisTemplate<String, String> redisTemplate,MsmService msmService){
        this.redisTemplate = redisTemplate;
        this.msmService = msmService;
    }

    @GetMapping("send/{phone}")
    public R sendMsm(@PathVariable String phone) {
        String code = redisTemplate.opsForValue().get(phone);
        if (StringUtils.isNotBlank(code)) {
            return R.ok().data("warning", "验证码已发送，请5分钟后重试");
        }
        code = RandomUtil.getFourBitRandom();
        if (msmService.isSend(code, phone)) {
            redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);    // 第三个参数为时间长度，第四个参数为单位，此意为存放5分钟
            return R.ok();
        }
        return R.invalidRequest();
    }

}
